package com.zj.osm.utils.db_utils

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Resources
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import com.blankj.utilcode.util.StringUtils.getStringArray
import com.zj.osm.App
import com.zj.osm.App.getInstances
import com.zj.osm.R
import com.zj.osm.bean.DefaultBean
import com.zj.osm.entity.db.EquipmentDao
import com.zj.osm.entity.db.LineDao
import com.zj.osm.entity.db.PointDao
import com.zj.osm.entity.greendao.Equipment
import com.zj.osm.entity.greendao.Line
import com.zj.osm.entity.greendao.Point
import com.zj.osm.entity.greendao.Project
import com.zj.osm.model.pojo.Equip
import com.zj.osm.model.pojo.Module
import com.zj.osm.model.pojo.ModuleType
import com.zj.osm.utils.SQLiteDatabaseUtils
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.MapView
import org.osmdroid.views.overlay.Marker
import java.util.*
import java.util.regex.Pattern
import kotlin.collections.ArrayList
import kotlin.math.log

@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class PointsUtils {
    //kotlin实现 懒加载模式单例模式。
    companion object {
        @SuppressLint("StaticFieldLeak")
        lateinit var mcontext: Context
        //单例模式
        val instance: PointsUtils by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            PointsUtils()
        }


        /***
         * 获取该项目对应所有点
         * itemID项目id
         */
        fun getItemPoints(itemId: Long, pointName: String): MutableList<Point>? {
            val itemPoints = App.getInstances().daoSession.pointDao.queryBuilder().where(PointDao.Properties.ProjectId.eq(itemId), PointDao.Properties.Name.eq(pointName)).build().list()
            return itemPoints;
        }

        fun getCurrentPoint(pointId: String, projectId: Long): Point {
            val currentPoint = App.getInstances().daoSession.pointDao.queryBuilder().where(PointDao.Properties.Uid.eq(pointId), PointDao.Properties.ProjectId.eq(projectId)).build().unique()
            return currentPoint
        }

        /**
         * itemId项目id
         * marName上一个点点Mark
         */
        fun getInPointsMaxNumber(itemId: Long, markName: String): String {
            var numberString = 1
            val itemPoints = getItemPoints(itemId, markName)
            for (index in 0 until itemPoints!!.size) {
                if (HasDigit(itemPoints.get(index).mark)) {//如果包含数字那么进行筛选最大值
                    var number = getNumberInString(itemPoints.get(index).mark, itemPoints.size)
                    if (numberString < number) {
                        numberString = number
                    }
                }

            }
            //替换拿到Mark里面的文字部分。

            return (numberString).toString()
        }

        /**
         * 点点编号问题
         * 1.这里最大点来解决。
         */
        fun getGlLine_bianhao(startP: Point, equip: Point, defaultMark: String, cid: Long, code: String,context: Context): String {
            val starId = startP.uid
            if (starId != null) {
                val points = getInstances().daoSession.pointDao.queryBuilder().where(PointDao.Properties.Uid.eq(starId)).build().unique()
                if (points != null && points.name != null && points.name == "杆塔" && equip.name == "杆塔") {
                    val strMark = points.mark
                    val regEx = "[0-9]+(?=[^0-9]*$)"
                    val p = Pattern.compile(regEx)
                    val m = p.matcher(strMark)
                    while (m.find()) {
                        Log.e("defaultMark", strMark.replace(regEx.toRegex(), (Integer.parseInt(m.group(0)) + 1).toString() + ""))
                        return strMark.replace(regEx.toRegex(), getInPointsMaxNumber(cid, equip.name))
                    }
                    return strMark + "-" + getInPointsMaxNumber(cid, equip.name);
                } else {
                    val endNumber = getInPointsMaxNumber(cid, equip.name)
                    return "$code-$endNumber"
                }
            }
            return defaultMark
        }

        fun getGlLine_ganxin(project: Project, startP: Point?, points0: Point,context: Context): Equipment? {
            mcontext=context
            val starId: String
            //先取关联杆塔选型信息
            if (startP != null && startP.uid != null && points0.name == "杆塔") {
                starId = startP.uid
                val points = getInstances().daoSession.pointDao.queryBuilder().where(PointDao.Properties.Uid.eq(starId)).build().unique()
                if (points != null && points0.name == "杆塔" && points.name == "杆塔") {
                    return getInstances().daoSession.equipmentDao.queryBuilder().where(EquipmentDao.Properties.PointId.eq(points.id), EquipmentDao.Properties.Qubie.eq(0)).build().unique()
                }
            }
            //取默认选型
            return if (points0.name.equals(mcontext.getString(R.string.map_tower))) {
                if (project.getGanxinModuleId()!=null&&project.getGanxinModuleId().length > 1) {
                    val defaultModel = getModuleLocal(project.getGanxinModuleId())
                    val defultModuleType = getModuleType(project.getGanxinModuleTypeId())
                    val ganxing = Equipment()
                    ganxing.qubie = 0
                    ganxing.moduleID = defaultModel!!.moduleID
                    ganxing.moduleTxt = defaultModel.moduleName
                    ganxing.name = defultModuleType!!.name
                    ganxing.threeName = defaultModel.moduleName
                    ganxing.threeId = defaultModel.moduleID
                    ganxing.moduleTxt = defaultModel.moduleName
                    ganxing.projectId = project.id
                    ganxing.lever_id = project.ganxinModuleTypeId
                    ganxing.head_id = project.ganxinModuleId
                    //杆高和杆型 Modle表的ModuleName
                    //资源文件来获取数据杆高
                    val ganGaoArray: Array<String> = getStringArray(R.array.gangao_array)
                    val ShaojingArray: Array<String> = getStringArray(R.array.shaojin_array)
                    for (i in ganGaoArray.indices) {
                        if (defaultModel.moduleName.contains(ganGaoArray[i])) {
                            ganxing.fourId = ganGaoArray[i] //杆高
                        }
                    }
                    for (i in ShaojingArray.indices) {
                        if (defaultModel.moduleName.contains(ShaojingArray[i])) {
                            ganxing.shaoJing = ShaojingArray[i] //稍经
                        }
                    }
                    ganxing.amount = 1
                    ganxing.module_code = defaultModel.moduleCode
                    ganxing
                } else {
                    null
                }
            } else null
        }

        private fun getNumberInString(mark: String?, pointNumber: Int): Int {
            var number = pointNumber
            val regEx = "[0-9]+(?=[^0-9]*$)"
            val p = Pattern.compile(regEx)
            val m = p.matcher(mark)
            while (m.find()) {
                number = m.group(0).toInt() + 1
            }
            return number
        }

        /***
         * 判断一个字符串是否含有数字
         * content:字符串内容
         */
        fun HasDigit(content: String): Boolean {
            var flag = false;
            var p = Pattern.compile(".*\\d+.*")
            var m = p.matcher(content)
            if (m.matches()) {
                flag = true;
            }
            return flag
        }

        fun isCouldNextT(jpoints: Point, cid: Long): Int {
            var mDataLines = ArrayList<Line>()
            val isTLine = getInstances().getDaoSession().lineDao.queryBuilder().where(LineDao.Properties.Item_id.eq(cid), LineDao.Properties.Start_id.eq(jpoints.uid), LineDao.Properties.ParallelPole.eq("1")).build().list()
            val isSzijieLine = getInstances().getDaoSession().lineDao.queryBuilder().where(LineDao.Properties.Item_id.eq(cid), LineDao.Properties.Start_id.eq(jpoints.uid), LineDao.Properties.ParallelPole.eq("2")).build().list()
            mDataLines.addAll(isTLine)
            mDataLines.addAll(isSzijieLine)
            if (isTLine.size >= 1) {
                return 1
            }
            return 0
        }

        fun isCouldNextSzj(jpoints: Point, cid: Long): Int {
            var mDataLines = ArrayList<Line>()
            val isTLine = getInstances().getDaoSession().lineDao.queryBuilder().where(LineDao.Properties.Item_id.eq(cid), LineDao.Properties.Start_id.eq(jpoints.uid), LineDao.Properties.ParallelPole.eq("1")).build().list()
            val isSzijieLine = getInstances().getDaoSession().lineDao.queryBuilder().where(LineDao.Properties.Item_id.eq(cid), LineDao.Properties.Start_id.eq(jpoints.uid), LineDao.Properties.ParallelPole.eq("2")).build().list()
            mDataLines.addAll(isTLine)
            mDataLines.addAll(isSzijieLine)
            if (mDataLines.size >= 2) {
                return 2
            }
            return 0
        }

        fun getNumberMarEnd(firstMarker: String): String {
            var endNumber = "1"
            if (HasDigit(firstMarker)) {//有数字
                //进行截取数字。
                endNumber = (getNumberM(firstMarker) + 1).toString()
            }
            return endNumber
        }

        fun getNumberM(stringHaveNumber: String): Int {
            var retureNumber = 1
            val regEx = "[0-9]+(?=[^0-9]*$)"
            val p = Pattern.compile(regEx)
            val m = p.matcher(stringHaveNumber)
            while (m.find()) {
                //获取字符串里面的最后的数字
                retureNumber = Integer.parseInt(m.group(0))
            }
            return retureNumber
        }

        ///查询线的remark
        fun getModuleLocal(reMarkerName: String): Module? {
            var module_array: Module? = null
            val sqLiteDatabase = SQLiteDatabaseUtils.getInstance().sqLiteDatabase
            assert(sqLiteDatabase != null)
            @SuppressLint("Recycle") val cursor = sqLiteDatabase!!.rawQuery("select * from Module m where m.ModuleID ='$reMarkerName'", null)//此处的db是表名，name是列名
            while (cursor.moveToNext()) {
                val module = Module()
                module.moduleID = cursor.getString(0)
                module.moduleName = cursor.getString(1)
                module.moduleTypeKey = cursor.getString(2)
                module.moduleCode = cursor.getString(3)
                module_array = module
            }

            cursor.close()
            return module_array
        }

        /**
         * @param
         * @return Equip
         */
        fun getModuleType(ModuleTypeID: String): ModuleType? {
            var strings: ModuleType? = null
            try {
                val sqLiteDatabase = SQLiteDatabaseUtils.getInstance().sqLiteDatabase
                @SuppressLint("Recycle") val cursor = sqLiteDatabase.rawQuery("select * from ModuleType mt where mt.ModuleTypeID ='$ModuleTypeID'", null)//此处的db是表名，name是列名
                while (cursor.moveToNext()) {
                    val equip = ModuleType()
                    equip.moduleTypeID = cursor.getString(0)
                    equip.name = cursor.getString(1)
                    equip.moduleTypeKey = cursor.getString(2)
                    strings = equip
                }
                cursor.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }

            return strings
        }

        /**
         * 获取数据库中的信息
         *
         * @param id id
         * @return 集合
         */
        fun getDefault(id: Int): List<DefaultBean?>? {
            var strings: MutableList<DefaultBean?>? = null
            try {
                strings = java.util.ArrayList<DefaultBean?>()
                val sqLiteDatabase = SQLiteDatabaseUtils.getInstance().sqLiteDatabase
                @SuppressLint("Recycle") val cursor = sqLiteDatabase.rawQuery("select * from DefaultXH where equipTypeID='$id'", null) //此处的db是表名，name是列名
                while (cursor.moveToNext()) {
                    val defaultBean = DefaultBean()
                    defaultBean.setUid(cursor.getString(0))
                    defaultBean.setModelTypeId(cursor.getInt(1))
                    defaultBean.setModelTypeName(cursor.getString(2))
                    defaultBean.setEquidTypeId(cursor.getInt(7))
                    defaultBean.setType(cursor.getString(8))
                    defaultBean.setDefaultType(cursor.getString(9))
                    defaultBean.setModleNum(cursor.getInt(10))
                    strings.add(defaultBean)
                }
                cursor.close()
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
            return strings
        }


        /**
         * @param str 查询的序号
         * @return Equip
         */
        fun getEquIp(context: Context, str: Int): MutableList<Equip>? {
            var strings: MutableList<Equip>? = null
            try {
                strings = java.util.ArrayList()
                val sqLiteDatabase = SQLiteDatabaseUtils.getInstance().sqLiteDatabase
                assert(sqLiteDatabase != null)
                @SuppressLint("Recycle") val cursor = sqLiteDatabase!!.rawQuery("select * from EquipType where component=$str", null)//此处的db是表名，name是列名
                while (cursor.moveToNext()) {
                    val equip = Equip()
                    equip.id = cursor.getInt(0)
                    equip.name = cursor.getString(1)
                    equip.component = cursor.getString(2)
                    equip.code = cursor.getString(3)
                    equip.defaultLineType = cursor.getString(4)
                    equip.icon = cursor.getString(5)
                    equip.remark = cursor.getString(6)
                    strings.add(equip)
                }
                cursor.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }

            return strings
        }


        /**
         * 求pOut在pLine以及pLine2所连直线上的投影点
         *
         * @param pLine
         * @param pLine2
         * @param pOut
         * @param
         */
        fun getProjectivePointNew(pLine: android.graphics.Point, pLine2: android.graphics.Point, pOut: android.graphics.Point): android.graphics.Point {
            Log.e("Point-S=", pLine.toString())
            Log.e("Point-E=", pLine2.toString())
            Log.e("Point-P=", pOut.toString())

            var k: Double
            try {
                k = getSlopeNew(pLine.x.toDouble(), pLine.y.toDouble(), pLine2.x.toDouble(), pLine2.y.toDouble())
            } catch (e: Exception) {
                k = 0.0
            }

            return getProjectivePointNew(pLine, k, pOut)
        }

        /**
         * 求直线外一点到直线上的投影点
         *
         * @param pLine 线上一点
         * @param k     斜率
         * @param pOut  线外一点
         * @param //    投影点
         */
        fun getProjectivePointNew(pLine: android.graphics.Point, k: Double, pOut: android.graphics.Point): android.graphics.Point {
            val pProject = android.graphics.Point()
            if (k == 0.0) {//垂线斜率不存在情况
                pProject.x = pOut.x
                pProject.y = pLine.y
            } else {
                pProject.x = ((k * pLine.x + pOut.x / k + pOut.y.toDouble() - pLine.y) / (1 / k + k)).toInt()
                pProject.y = (-1 / k * (pProject.x - pOut.x) + pOut.y).toInt()
            }

            Log.e("Point-Pp=", pProject.toString())
            return pProject
        }

        /**
         * 通过两个点坐标计算斜率
         * 已知A(x1,y1),B(x2,y2)
         * 1、若x1=x2,则斜率不存在；
         * 2、若x1≠x2,则斜率k=[y2－y1]/[x2－x1]
         *
         * @param x1
         * @param y1
         * @param x2
         * @param y2
         * @throws Exception 如果x1==x2,则抛出该异常
         */
        @Throws(Exception::class)
        fun getSlopeNew(x1: Double, y1: Double, x2: Double, y2: Double): Double {
            if (x1 == x2) {
                throw Exception("Slope is not existence,and div by zero!")
            }
            return (y2 - y1) / (x2 - x1)
        }


        fun getPointMark_bianhao(startP: Point, equip: Point, defaultMark: String): String {
            val starId = startP.uid
            if (starId != null) {
                val points = getInstances().daoSession.pointDao.queryBuilder().where(PointDao.Properties.Uid.eq(starId)).build().unique()
                if (points != null && points.name != null && points.name.equals(equip.name)) {
                    val strMark = points.mark
                    val regEx = "[0-9]+(?=[^0-9]*$)"
                    val p = Pattern.compile(regEx)
                    val m = p.matcher(strMark)

                    while (m.find()) {
                        Log.e("defaultMark", strMark.replace(regEx.toRegex(), (Integer.parseInt(m.group(0)) + 1).toString() + ""))
                        return strMark.replace(regEx.toRegex(), (Integer.parseInt(m.group(0)) + 1).toString() + "")
                    }
                } else if (points != null && points.name != null && (!points.name.equals(equip.name))) {//如果前后两个不是统一类型就获取1后面点。
                    val strMark = points.mark
                    val mNameString = equip.mark
                    val regEx = "[0-9]+(?=[^0-9]*$)"
                    val p = Pattern.compile(regEx)
                    val m = p.matcher(strMark)
                    while (m.find()) {
                        val description = Pattern.compile("[\\d]").matcher(mNameString).replaceAll("")
                        Log.e("defaultMark", description + "")
                        return description + ((Integer.parseInt(m.group(0)) + 1).toString())// strMark.replace(regEx.toRegex(), (Integer.parseInt(m.group(0)) + 1).toString() + "")
                    }
                } else {
                    return defaultMark
                }
            }
            return defaultMark
        }


    }

    /**
     * 获取UUID
     *
     * @return uuid
     */
    fun getUUID(): String? {
        return UUID.randomUUID().toString()
    }

    /**
     *绘制杆塔等的样式
     *@param p
     *@param content
     *@param mMapView
     */
    @SuppressLint("DefaultLocale")
    fun getPointMarker(p: Point, content: Context, mMapView: MapView): Marker {
        val resourceName = StringBuilder()
        when (p.getState()) {
            "原有" -> resourceName.append("y_")
            "改造" -> resourceName.append("c_")
            "拆除" -> resourceName.append("g_")
            else -> resourceName.append("c_")
        }
        if (p.getIcon() == null) {
            resourceName.append("zxg")
        } else {
            if (p.getIsT() == null) {
                resourceName.append(p.icon.toLowerCase())
            } else {
                if (p.getIsT() == "1" || p.getIsT() == "2") {
                    resourceName.append("f")
                } else {
                    if(p.icon == "XHGD" || p.icon == "DLGD"){
                        resourceName.append("dlxhgd")
                    }else{
                        resourceName.append(p.getIcon().toLowerCase())

                    }
                }
            }
        }
        val res: Resources = content.resources
        var i = res.getIdentifier(resourceName.toString(), "drawable", content.packageName)
        if (i == 0) {
            i = res.getIdentifier("x_dxd", "drawable", content.packageName)
        }
        /***
         * 这个是杆塔/底薪点/设备的图标。
         * */
        /***
         * 这个是杆塔/底薪点/设备的图标。
         */
        val bitmap: Drawable = content.resources.getDrawable(i)
        //var drawable = VectorDrawableCompat.create(content.resources, R.drawable.c_xsb, null);
        val poiMarker = Marker(mMapView)
        poiMarker.title = p.mark
        //这句话可以设置点击时候地图中点是否移动到地图中央。
        //这句话可以设置点击时候地图中点是否移动到地图中央。
        poiMarker.setPanToView(false)
        poiMarker.icon = bitmap
        //这句话能让Mark来规定自己位置。anchorU和anchorV  0-1之间右下角到左上角走。
        //这句话能让Mark来规定自己位置。anchorU和anchorV  0-1之间右下角到左上角走。
        poiMarker.setAnchor(0.4f, 0.4f)
        //这句话特么烦死人。
        //这句话特么烦死人。
        poiMarker.position = GeoPoint(p.getLatitude(), p.getLongitude())
        poiMarker.id=p.uid
        poiMarker.relatedObject=p
        return poiMarker
    }

    /**
     *这个是杆塔/底薪点/设备的mark名称
     *@param mMapView
     *@param p
     *@param WHETHER_TO_DISPLAY_THE_NUMBER
     */
    fun getPointMarkerNameMarker(mMapView: MapView, p: Point, WHETHER_TO_DISPLAY_THE_NUMBER: Boolean): Marker {
        /**
         * 这个是杆塔/底薪点/设备的mark名称
         */
        val m = Marker(mMapView)
        m.id = p.uid
        m.title = p.mark
        m.setPanToView(false) //点击时地图中点是否移动到地图中央。
        m.setOnMarkerClickListener { marker: Marker?, mapView: MapView? -> false }
        m.position = GeoPoint(p.getLatitude(), p.getLongitude())
        m.textLabelBackgroundColor = Color.TRANSPARENT
        m.textLabelFontSize = 40
        m.textLabelForegroundColor = Color.rgb(60, 60, 60)
        if(p.high!=null&&!p.high.equals("null")&&!p.high.equals(" ")&& p.high.isNotEmpty()){
        m.setTextIcon((p.high.toDouble().toInt()).toString() + "m")
        }else{
            m.setTextIcon("0m")

        }
        m.relatedObject = p
        m.setAnchor(0.6f, 2.2f)
        m.setVisible(WHETHER_TO_DISPLAY_THE_NUMBER)
        return m
    }

    fun getPointEquipmentMarks(marker: Marker, context: Context, mMapView: MapView, WHETHER_TO_DISPLAY_THE_NUMBER: Boolean):Marker {
        val p = marker.relatedObject as Point
        val view = View.inflate(context, R.layout.activity_map_scenic_maker, null)
        val map_marker = view.findViewById<TextView>(R.id.map_marker)
        val map_marker_xinhao = view.findViewById<TextView>(R.id.map_marker_xinhao)
        //住上设备
        //住上设备
        val map_marker_zhushang = view.findViewById<ImageView>(R.id.map_marker_zhushang)
        val equipmenttext = getInstances().daoSession.equipmentDao.queryBuilder().where(EquipmentDao.Properties.PointId.eq(p.id), EquipmentDao.Properties.Qubie.eq(0)).build().list()
        if (equipmenttext.size > 0 && equipmenttext[0].fourId != null && equipmenttext[0].fourId != "全部") {
            map_marker_xinhao.text = if (equipmenttext[0].fourId != "null") equipmenttext[0].fourId else ""
        }
        val equipmentZhushang = getInstances().daoSession.equipmentDao.queryBuilder().where(EquipmentDao.Properties.PointId.eq(p.id), EquipmentDao.Properties.Qubie.eq(2)).build().list()
        if (equipmentZhushang != null && equipmentZhushang.size > 0) {
            map_marker_zhushang.visibility = View.VISIBLE
            when (equipmentZhushang[0].name) {
                "柱上断路器" -> map_marker_zhushang.setBackgroundResource(R.drawable.zs_zsdlq)
                "柱上负荷开关" -> map_marker_zhushang.setBackgroundResource(R.drawable.zs_zsfhkg)
                "柱上隔离开关" -> map_marker_zhushang.setBackgroundResource(R.drawable.zs_zsglkg)
                "柱上避雷器" -> map_marker_zhushang.setBackgroundResource(R.drawable.zs_zsblq)
                "跌落式熔断器" -> map_marker_zhushang.setBackgroundResource(R.drawable.zs_dlsrdq)
                "故障指示器" -> map_marker_zhushang.setBackgroundResource(R.drawable.zs_zsdrq)
                "拉线" -> map_marker_zhushang.setBackgroundResource(R.drawable.zs_ls)
                else -> map_marker_zhushang.setBackgroundResource(R.drawable.zs_zsdlq)
            }
        } else {
            map_marker_zhushang.visibility = View.GONE
        }
        map_marker.text = if (p.mark == null) "" else p.mark
        val bitmap: Bitmap = createBitmap3(view, 150, 500)
        val drawable: Drawable = BitmapDrawable(bitmap)
        val lineTypeMarker = Marker(mMapView)
        lineTypeMarker.setPanToView(false)
        lineTypeMarker.setOnMarkerClickListener { markers: Marker?, mapView: MapView? -> false }
        lineTypeMarker.position = GeoPoint(p.latitude, p.longitude) //设置显示位置
        lineTypeMarker.id=p.uid
        lineTypeMarker.relatedObject=p
        lineTypeMarker.textLabelBackgroundColor = Color.alpha(0)
        lineTypeMarker.textLabelFontSize = 35
        lineTypeMarker.icon = drawable
        lineTypeMarker.setAnchor(1.52f, 0.76f) //Ux轴如果大左  Vy轴如果大就向上小下
        lineTypeMarker.setVisible(WHETHER_TO_DISPLAY_THE_NUMBER)
        return lineTypeMarker;
    }

    private fun createBitmap3(v: View, width: Int, height: Int): Bitmap{ //测量使得view指定大小
        val measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY)
        val measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)
        v.measure(measuredWidth, measuredHeight)
        //调用layout方法布局后，可以得到view的尺寸大小
        v.layout(0, 0, v.measuredWidth, v.measuredHeight)
        val bmp = Bitmap.createBitmap(v.width, v.height, Bitmap.Config.ARGB_8888)
        val c = Canvas(bmp)
        c.drawColor(Color.alpha(0))
        v.draw(c)
        return bmp
    }
    //获取水泥制品module
    fun getAllMoudle(moduleTypeKey: String): ArrayList<Module> {
        val allModule = ArrayList<Module>()
        val db = SQLiteDatabaseUtils.getInstance().sqLiteDatabase!!

        @SuppressLint("Recycle")
        val cursor = db.rawQuery("select ModuleID,ModuleName,ModuleTypeKey,ModuleCode,ModuleCode from Module  where ModuleTypeKey='$moduleTypeKey' and State=${"1"}", null) //此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            val module = Module()
            module.moduleID = cursor.getString(0)
            module.moduleName = cursor.getString(1)
            module.moduleTypeKey = cursor.getString(2)
            module.moduleCode = cursor.getString(3)
            //根据moduleID和key=SFCTH 是否成套化
            //根据moduleID和key=
            allModule.add(module)
        }
        cursor.close()
        return allModule
    }
    fun getAllMoudleTypeOfBoxChange(moduTypkeyArray: Array<Int>): ArrayList<ModuleType> {
        val moduleTypeData = ArrayList<ModuleType>()
        val db = SQLiteDatabaseUtils.getInstance().sqLiteDatabase
        var cursor: Cursor? = null
        for (index in moduTypkeyArray.indices) {
            @SuppressLint("Recycle")
            cursor = db.rawQuery("select mt.* from moduletype mt left join equip_moduleType ematt on mt.ModuleTypeID = ematt.ModuletypeID where ematt.equipID = '${moduTypkeyArray[index]}' ORDER BY ematt.id", null) //此处的db是表名，name是列名
            while (cursor.moveToNext()) {
                val moduleType = ModuleType()
                moduleType.moduleTypeID = cursor.getString(0)
                moduleType.name = cursor.getString(1)
                moduleType.moduleTypeKey = cursor.getString(2)
                moduleType.parentKey = cursor.getString(3)
                moduleType.ico = cursor.getString(6)
                //moduleType.setState(cursor.getString(4));
                //这里去掉了故障指示器(361)改成了(3611)
                if (moduleType.name != null) {
                    moduleTypeData.add(moduleType)
                }
            }
        }
        cursor?.close()
        return moduleTypeData
    }
    //获取所有
    fun getAllMoudleType(arrayList: Array<String>): ArrayList<ModuleType> {
        var moduleModuleAll = ArrayList<ModuleType>()
        var cursor: Cursor? = null
        for (index in arrayList.indices) {
            val db = SQLiteDatabaseUtils.getInstance().sqLiteDatabase!!
            @SuppressLint("Recycle")
            cursor = db.rawQuery("select ModuleTypeID,ModuleTypeName,ModuleTypeKey from ModuleType  where ModuleTypeKey='${arrayList[index]}' and State=${"1"}", null) //此处的db是表名，name是列名
            while (cursor.moveToNext()) {
                val moduleType = ModuleType()
                moduleType.moduleTypeID = cursor.getString(0)
                moduleType.name = cursor.getString(1)
                moduleType.moduleTypeKey = cursor.getString(2)
                moduleModuleAll.add(moduleType)
            }
        }
        cursor!!.close()
        return moduleModuleAll
    }
}